package com.example.redissondemo.controller;

import com.example.redissondemo.util.LockUtil;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.MessageFormat;

@RestController
@Slf4j
public class RedissonController {

    @GetMapping("/test/lock")
    public void test() throws InterruptedException {
        log.info("test,当前线程：{}", Thread.currentThread().getName());
        //加锁 同一个用户同一时间只能处理一次
        String userLockKey = MessageFormat.format("userLock:{0}", "test");
        boolean lockSuccess = LockUtil.tryLock(userLockKey, 10, 30);
        if (!lockSuccess) {
            log.error("lock fail");
            return;
        }
        try {
            Thread.sleep(1000);
        } catch (Exception e){
            log.error("test error", e);
        }
        finally {
            //释放锁
            LockUtil.unlock(userLockKey);
        }
    }
}
